from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from rest_framework.response import Response
from decimal import Decimal
from rest_framework.generics import CreateAPIView

from goods.models import SKU
from . import serializers


# 订单详情之去结算
class OrderSettlementView(APIView):
    # jwt验证通过用户才可以进入订单界面
    permission_classes = [IsAuthenticated]

    def get(self, request):

        user = request.user
        # 获取redis中的被勾选的购物车数据
        redis_conn = get_redis_connection('carts')
        redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
        redis_selected = redis_conn.smembers('selected_%s' % user.id)

        cart = {}
        for sku_id in redis_selected:
            cart[int(sku_id)] = int(redis_cart_dict[sku_id])
        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        serializer = serializers.OrderSettlementSerializer({'freight':freight, 'skus':skus})
        return Response(serializer.data)


class CommitOrderView(CreateAPIView):
    """提交订单"""
    # 登录⽤用户才能访问
    permission_classes = [IsAuthenticated]
    # 指定序列列化器器
    serializer_class = serializers.CommitOrderSerializer